<template>
  <div class="chat-window" :class="{ 'keyboard-active': isKeyboardVisible }">
    <div class="messages" ref="messagesContainer">
      <MessageItem
        v-for="message in store.messages"
        :key="message.id"
        :message="message"
        :sender="getSender(message.sender)"
      />
    </div>
    <MessageInput @focus="onInputFocus" @blur="onInputBlur" />
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { useChatStore } from '../stores/chat'
import MessageItem from './MessageItem.vue'
import MessageInput from './MessageInput.vue'
import type { User } from '../types'

const store = useChatStore()
const messagesContainer = ref<HTMLElement | null>(null)
const isKeyboardVisible = ref(false)

const getSender = (senderId: string): User => {
  if (senderId === store.currentUser.id) {
    return store.currentUser
  }
  return {
    id: senderId,
    name: 'Other User'
  }
}

const scrollToBottom = (immediate = false) => {
  const scroll = () => {
    if (messagesContainer.value) {
      const { scrollHeight, clientHeight } = messagesContainer.value
      const maxScrollTop = scrollHeight - clientHeight
      const behavior = immediate ? 'auto' : 'smooth'
      
      messagesContainer.value.scrollTo({
        top: maxScrollTop,
        behavior
      })
    }
  }

  if (immediate) {
    scroll()
  } else {
    setTimeout(scroll, 100)
  }
}

// 监听消息变化，自动滚动到底部
watch(() => store.messages.length, () => {
  scrollToBottom()
})

const onInputFocus = () => {
  isKeyboardVisible.value = true
  scrollToBottom(true)
}

const onInputBlur = () => {
  isKeyboardVisible.value = false
}
</script>

<style scoped>
.chat-window {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: 100%;
  transition: height 0.3s ease-out;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 1rem 0;
  background: #f5f5f5;
  -webkit-overflow-scrolling: touch; /* iOS 滚动优化 */
  overscroll-behavior: contain; /* 防止 iOS 橡皮筋效果 */
}

.messages::-webkit-scrollbar {
  width: 4px;
}

.messages::-webkit-scrollbar-track {
  background: transparent;
}

.messages::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 2px;
}

@media (max-width: 768px) {
  .chat-window.keyboard-active {
    height: calc(100% - var(--keyboard-height, 0px));
  }
  
  .messages {
    padding: 0.5rem 0;
    overscroll-behavior: contain; /* 防止 iOS 橡皮筋效果 */
  }
}
</style> 